const uuid = require("uuid")
const BetterSqlite3 = require("./BetterSqlite3")
class BaseService {
  constructor() {
    this.db = new BetterSqlite3({ sqlcriper: false })
  }
  /**
   * 分页查询
   * @param {*} args.tableName 表名
   * @param {*} args.filter sql条件语句
   * @param {*} args.page 开始页
   * @param {*} args.pageSize 每页条数
   * @returns
   * {
   *    total: 100
   *    page: 1
   *    pageSize: 10
   *    rows: []
   * }
   */
  getListByPage({ tableName, filter, page = 1, pageSize = 10 } = {}) {
    const total = this.db.getCount(`SELECT count(1) as count FROM ${tableName} ${filter || ""}`)
    const rows = this.db.getAll(`SELECT * FROM ${tableName} ${filter || ""} LIMIT ${(page - 1)*pageSize},${pageSize}`)
    return {
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      rows,
    }
  }
  getOneById(tableName, id) {
    return this.db.getOne(`SELECT * FROM ${tableName} WHERE id=?`, id)
  }
  insert(tableName, data) {
    const columns = Object.keys(data)
    const columnPads = columns.map((v) => "?").join(",")
    const vals = columns.map((v) => data[v])
    this.db.checkTableAndColumns(tableName, columns)
    const sql = `INSERT INTO ${tableName} (${columns.join(",")}) VALUES (${columnPads})`
    return this.db.insert(sql, ...vals)
  }
}

module.exports = BaseService
